package me.xujl;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.apache.commons.dbcp.BasicDataSource;


/**
 * ETL example from java code
 */
public class EtlRouteBuilder extends RouteBuilder {

    public void configure() {

        from("direct:start")
            .setBody(simple("select * from test1 "))
            .to("jdbc:src_db?statement.fetchSize=-2147483648&readSize=10")
            .split(body())
            .setHeader("row", body())
            .setBody(simple("select count(1) from test2 where id = '${headers.row['id']}'"))
            .to("jdbc:dest_db?outputType=SelectOne")
            .choice()
            .when(body().isEqualTo(0))
            .setBody(simple("insert into test2(id, content) value('${headers.row['id']}','${headers.row['content']}')"))
            .otherwise()
            .setBody(simple("update test2 set content = '${headers.row[content]}' where id = '${headers.row[id]}'"))
            .end()
            .log("${body}")
            .to("jdbc:dest_db")
            .setBody(simple("date:now"));


        //from("timer://myTimer?period=2000")
        //.simple("Current time is ${header.firedTime}").to("log:out");
    }

    /**
     * A main() so we can easily run these routing rules in our IDE
     */
    public static void main(String... args) throws Exception {
        test1();
    }

    private static void test1() throws Exception {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8");
        ds.setUsername("root");
        ds.setPassword("");


        SimpleRegistry registry = new SimpleRegistry();
        registry.put("src_db", ds);
        registry.put("dest_db", ds);

        CamelContext camelContext = new DefaultCamelContext(registry);
        camelContext.addRoutes(new EtlRouteBuilder());
        camelContext.start();

        ProducerTemplate template = camelContext.createProducerTemplate();
        template.sendBody("direct:start", "whatever");

        camelContext.stop();
    }

}